<template>
  <MyModal ref="myModal" title="新增智能问答" :top="40" :width="600">
    <template #content>
      <div style="display: grid; place-items: center">
        <a-form ref="loginForm" :model="formState" :label-col="labelCol" style="width: 400px">
          <a-form-item
            has-feedback
            name="keyword"
            label="触发关键字"
            help="只允许汉字、数字、字母，不要填写符号"
          >
            <a-input v-model:value="formState.keyword" placeholder="触发关键字"></a-input>
          </a-form-item>

          <a-form-item has-feedback name="keyword" label="回复类型" style="margin-top: 15px">
            <a-select v-model:value="formState.type" placeholder="请选择" style="width: 200px">
              <a-select-option v-for="(item, index) in typeList" :key="index" :value="item.value">
                {{ item.label }}
              </a-select-option>
            </a-select>
          </a-form-item>

          <a-form-item
            v-if="formState.type == '1'"
            has-feedback
            name="content"
            label="回复文本消息"
          >
            <a-textarea
              :rows="5"
              v-model:value="formState.content"
              autocomplete="off"
              style="max-height: 456px"
            ></a-textarea>
          </a-form-item>

          <a-form-item
            v-if="formState.type == '2'"
            has-feedback
            name="content"
            label="回复图片消息"
          >
            <!--
                action="http://ticket-expert-api.liangpiaovip.com/platform/wechatReply/uploadToAliOss"
                action="http://k8s-cluster.liangpiaovip.com:30080/ticket-expert/platform/wechatReply/uploadToAliOss"    
              -->
            <a-upload
              action="http://crm.liangpiaovip.com/platform/wechatReply/uploadToAliOss"
              :beforeUpload="handleBeforeUpload"
              :customRequest="customRequest"
              list-type="picture"
              v-model:file-list="fileLists"
              @change="handleChange"
            >
              <a-button style="border-radius: 6px">
                <upload-outlined></upload-outlined>
                上传图片
              </a-button>
            </a-upload>
          </a-form-item>

          <a-form-item style="text-align: right">
            <a-button style="margin-right: 10px; border-radius: 6px" @click="myModal.cancelModal()">
              取消
            </a-button>
            <a-button type="primary" style="border-radius: 6px" @click="handleSubmit">
              完成
            </a-button>
          </a-form-item>
        </a-form>
      </div>
    </template>
  </MyModal>
</template>

<script setup lang="ts">
import { ref } from 'vue'
import { useUserStore } from '@/store/modules/user'

const userStore = useUserStore()

const myModal = ref()

const rowInfo = ref<any>({})
const showModal = (record: any = {}) => {
  rowInfo.value = {}

  if (Object.keys(record).length > 0) {
    rowInfo.value = record
    // console.log('rowInfo=', rowInfo.value)

    formState.value.content = rowInfo.value!.content
    formState.value.keyword = rowInfo.value!.keyword
    formState.value.type = rowInfo.value!.replyType
  }

  myModal.value?.showModal()
}

const emit = defineEmits<{
  refresh: [params: formState]
}>()

defineExpose({
  showModal,
})

let labelCol = { span: 6 }
interface formState {
  keyword: string
  type: string
  content: string
}
const formState = ref<formState>({
  keyword: '',
  type: '',
  content: '',
})
import type { SelectProps } from 'ant-design-vue'
const typeList = ref<SelectProps['options']>([
  {
    label: '文本',
    value: 1,
  },
  {
    label: '图片',
    value: 2,
  },
])

const fileLists = ref<Array<any>>([])
const handleBeforeUpload = (file: any, fileList: any) => {
  // console.log('file=', file)
  // console.log('fileList=', fileList)
  fileLists.value = fileList
  return true
}

const customRequest = (option: any) => {
  const { onSuccess, onError, file, action, data = {} } = option

  // 自定义参数名
  const formData = new FormData()
  formData.append('file', file)
  formData.append('type', '2')

  // 添加其他自定义数据
  // Object.keys(data).forEach(key => {
  //   formData.append(key, data[key])
  // })

  fetch(action, {
    headers: {
      'User-Token': localStorage.getItem('token') as any,
    },
    method: 'POST',
    body: formData,
  })
    .then(response => response.json())
    .then(result => {
      onSuccess(result, file)
      // console.log('result=', result)
      // console.log('file=', file)
      formState.value.content = result.data
    })
    .catch(error => {
      onError(error)
    })
}

const handleChange = (info: any) => {
  // console.log('info=', info)
  let resFileList = [...info.fileList]
  resFileList = resFileList.map(file => {
    if (file.response) {
      file.url = file.response.data
    }
    return file
  })
  fileLists.value = resFileList
}

const replaceEnglishSymbolsWithChinese = text => {
  // 定义英文符号到中文符号的映射
  const symbolMap = {
    '.': '。',
    ',': '，',
    '?': '？',
    '!': '！',
    ':': '：',
    ';': '；',
    '(': '（',
    ')': '）',
    // '[': '【',
    // ']': '】'
    '{': '｛',
    '}': '｝',
    '"': '“',
    "'": '’',
    '`': '‘',
    // '—': '——',
    // '-': '－',
    // '_': '＿',
    // '/': '／',
    '\\': '＼',
    // '|': '｜',
    // '@': '＠',
    // '#': '＃',
    // '$': '＄',
    // '%': '％',
    // '^': '＾',
    // '&': '＆',
    // '*': '＊',
    // '=': '＝',
    // '+': '＋',
    // '<': '＜',
    // '>': '＞'

    /* 注意：这里没有包括 '~'，因为 '~' 在中文中通常不作为标点符号使用
        如果需要替换，可以添加：'~': '～' */
  }
  return text.replace(/[.,!?;:(){}\[\]"`—_\/\\|@#$%^&*=+<>]/g, function (match) {
    return symbolMap[match] || match // 如果找不到对应的中文符号，则返回原符号
  })
}

const handleSubmit = async () => {
  console.log('formState.value.content=', formState.value.content)
  let originalText = ''
  if(formState.value.content.indexOf('ticket-expert-image-1323418546') == -1){
    originalText = replaceEnglishSymbolsWithChinese(formState.value.content)
  } else {
    originalText = formState.value.content
  }

  let params = {
    createTime: Date.now(),
    updateTime: Date.now(),
    identifying: Math.random().toString(36).substr(2),
    keyword: formState.value.keyword,
    content: originalText,
    type: formState.value.type,
    flag: false,
  }

  if (Object.keys(rowInfo.value).length > 0) {
    params.flag = true
    params.identifying = rowInfo.value.identifying
  }

  // console.log('params=', params)

  emit('refresh', params)
  myModal.value.cancelModal()
}
</script>
